<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生信息管理系统</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C',
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .menu-active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }
            .sidebar {
                @apply fixed top-0 left-0 h-full w-64 bg-white shadow-lg transform -translate-x-full md:translate-x-0 transition-transform duration-300 z-20;
            }
            .sidebar-overlay {
                @apply fixed inset-0 bg-black bg-opacity-50 z-10 hidden md:hidden;
            }
            .main-content {
                @apply min-h-screen md:ml-64 transition-all duration-300;
            }
            .card {
                @apply bg-white rounded-lg shadow-md p-5 hover:shadow-lg;
            }
            .btn {
                @apply px-4 py-2 rounded-md transition-all duration-200 font-medium;
            }
            .btn-primary {
                @apply bg-primary text-white hover:bg-primary/90;
            }
            .input {
                @apply px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50;
            }
        }
    </style>
</head>
<body class="font-sans bg-gray-50 flex flex-col min-h-screen">
<!-- 侧边栏 -->
<div class="sidebar" id="sidebar">
    <div class="p-4 border-b flex items-center justify-between">
        <div class="flex items-center space-x-2">
            <i class="fa fa-graduation-cap text-primary text-2xl"></i>
            <h1 class="text-lg font-bold text-gray-800">学生管理</h1>
        </div>
        <button class="md:hidden text-gray-500 hover:text-gray-700" id="close-sidebar">
            <i class="fa fa-times"></i>
        </button>
    </div>
    <div class="overflow-y-auto h-[calc(100vh-64px)]" id="menu-container">
        <div class="p-4 text-center text-gray-500">
            <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
            <p>加载菜单中...</p>
        </div>
    </div>
</div>

<!-- 侧边栏遮罩层 -->
<div class="sidebar-overlay" id="sidebar-overlay"></div>

<!-- 主内容区 -->
<div class="main-content flex-1">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm fixed top-0 right-0 left-0 md:left-64 z-10 transition-all duration-300">
        <div class="flex items-center justify-between px-6 py-3">
            <div class="flex items-center">
                <button class="mr-4 text-gray-500 md:hidden" id="open-sidebar">
                    <i class="fa fa-bars"></i>
                </button>
            </div>

            <div class="flex items-center space-x-4">
                <div class="flex items-center space-x-2 cursor-pointer" id="user-menu-button">
                    <span class="text-gray-700 font-medium" id="user-name">管理员</span>
                    <i class="fa fa-angle-down text-gray-500"></i>
                </div>
            </div>
        </div>
    </header>

    <!-- 用户菜单 -->
    <div class="hidden fixed top-16 right-6 bg-white rounded-lg shadow-lg z-20 p-2 w-48" id="user-menu">
        <a href="#" class="flex items-center px-3 py-2 text-gray-700 hover:bg-gray-50 rounded-md" onclick="openEditNameModal()">
            <i class="fa fa-user-circle mr-3 text-gray-500"></i>
            <span>修改名称</span>
        </a>
        <div class="border-t my-1"></div>
        <a href="#" class="flex items-center px-3 py-2 text-gray-700 hover:bg-gray-50 rounded-md text-danger" onclick="logout()">
            <i class="fa fa-sign-out mr-3"></i>
            <span>退出登录</span>
        </a>
    </div>

    <!-- 修改名称模态框 -->
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden" id="edit-name-modal">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 transform transition-all">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-gray-800">修改名称</h3>
                <button class="text-gray-500 hover:text-gray-700" onclick="closeEditNameModal()">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">新名称</label>
                <input type="text" id="new-name" class="input w-full" placeholder="请输入新名称" value="管理员">
            </div>
            <div class="flex justify-end space-x-3">
                <button class="btn btn-outline" onclick="closeEditNameModal()">取消</button>
                <button class="btn btn-primary" onclick="saveName()">保存</button>
            </div>
        </div>
    </div>

    <!-- 操作成功提示 -->
    <div class="fixed bottom-6 right-6 bg-success text-white px-4 py-2 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-500 flex items-center" id="success-toast">
        <i class="fa fa-check-circle mr-2"></i>
        <span id="toast-message">操作成功</span>
    </div>

    <!-- 页面内容 -->
    <main class="pt-20 pb-10 px-6">
        <div class="mb-6">
            <h2 class="text-2xl font-bold text-gray-800" id="page-title">仪表盘</h2>
            <p class="text-gray-500 mt-1" id="page-description">欢迎使用学生信息管理系统</p>
        </div>

        <!-- 快捷操作 -->
        <div class="card mb-8">
            <h3 class="font-bold text-gray-800 mb-5">快捷操作</h3>
            <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
                <a href="javascript:void(0)" class="flex flex-col items-center justify-center p-4 bg-primary/5 rounded-lg hover:bg-primary/10 transition-colors" onclick="loadPage('/student/add', '添加学生', this)">
                    <div class="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mb-2">
                        <i class="fa fa-user-plus text-primary text-xl"></i>
                    </div>
                    <span class="text-sm text-gray-700">添加学生</span>
                </a>
                <a href="javascript:void(0)" class="flex flex-col items-center justify-center p-4 bg-warning/5 rounded-lg hover:bg-warning/10 transition-colors" onclick="loadPage('/teacher/add', '添加教师', this)">
                    <div class="w-12 h-12 bg-warning/10 rounded-full flex items-center justify-center mb-2">
                        <i class="fa fa-user-plus text-warning text-xl"></i>
                    </div>
                    <span class="text-sm text-gray-700">添加教师</span>
                </a>
                <a href="javascript:void(0)" class="flex flex-col items-center justify-center p-4 bg-info/5 rounded-lg hover:bg-info/10 transition-colors" onclick="loadPage('/course/add', '添加课程', this)">
                    <div class="w-12 h-12 bg-info/10 rounded-full flex items-center justify-center mb-2">
                        <i class="fa fa-book text-info text-xl"></i>
                    </div>
                    <span class="text-sm text-gray-700">添加课程</span>
                </a>
            </div>
        </div>

        <!-- 内容区域 -->
        <div class="card">
            <div class="text-center py-8">
                <h3 class="text-xl font-medium text-gray-700 mb-2">系统概览</h3>
                <p class="text-gray-500">请从左侧菜单选择您要访问的功能</p>
            </div>
        </div>
    </main>
</div>

<!-- 真正的页脚 -->
<footer class="bg-white py-4 px-6 border-t">
    <div class="flex justify-center items-center">
        <p class="text-gray-500 text-sm text-center">© 2025 学生信息管理系统</p>
    </div>
</footer>

<!-- JavaScript -->
<script>
    // 侧边栏控制
    document.getElementById('open-sidebar').addEventListener('click', function() {
        document.getElementById('sidebar').classList.remove('-translate-x-full');
        document.getElementById('sidebar-overlay').classList.remove('hidden');
    });

    document.getElementById('close-sidebar').addEventListener('click', function() {
        document.getElementById('sidebar').classList.add('-translate-x-full');
        document.getElementById('sidebar-overlay').classList.add('hidden');
    });

    document.getElementById('sidebar-overlay').addEventListener('click', function() {
        document.getElementById('sidebar').classList.add('-translate-x-full');
        document.getElementById('sidebar-overlay').classList.add('hidden');
    });

    // 用户菜单控制
    document.getElementById('user-menu-button').addEventListener('click', function(e) {
        e.stopPropagation();
        const userMenu = document.getElementById('user-menu');
        userMenu.classList.toggle('hidden');
    });

    // 点击其他地方关闭用户菜单
    document.addEventListener('click', function(e) {
        const userMenu = document.getElementById('user-menu');
        if (!userMenu.classList.contains('hidden')) {
            userMenu.classList.add('hidden');
        }
    });

    // 修改名称相关函数
    function openEditNameModal() {
        document.getElementById('edit-name-modal').classList.remove('hidden');
        document.getElementById('user-menu').classList.add('hidden');
    }

    function closeEditNameModal() {
        document.getElementById('edit-name-modal').classList.add('hidden');
    }

    function saveName() {
        const newName = document.getElementById('new-name').value.trim();
        if (newName) {
            document.getElementById('user-name').textContent = newName;
            closeEditNameModal();
            showToast('名称修改成功');
        } else {
            showToast('名称不能为空', false);
        }
    }

    // 退出登录
    function logout() {
        if (confirm('确定要退出登录吗？')) {
            localStorage.removeItem('token');
            showToast('已成功退出登录');
            setTimeout(() => {
                window.location.href = '/login';
            }, 1500);
        }
    }

    // 显示提示消息
    function showToast(message, isSuccess = true) {
        const toast = document.getElementById('success-toast');
        const toastMessage = document.getElementById('toast-message');

        toastMessage.textContent = message;
        if (!isSuccess) {
            toast.classList.remove('bg-success');
            toast.classList.add('bg-danger');
        } else {
            toast.classList.remove('bg-danger');
            toast.classList.add('bg-success');
        }

        toast.classList.remove('translate-y-20', 'opacity-0');

        setTimeout(() => {
            toast.classList.add('translate-y-20', 'opacity-0');
        }, 3000);
    }

    // 从后端加载菜单数据
    function loadMenu() {
        const menuContainer = document.getElementById('menu-container');

        // 显示加载中状态
        menuContainer.innerHTML = `
            <div class="p-4 text-center text-gray-500">
                <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
                <p>加载菜单中...</p>
            </div>
        `;

        // 获取token（如果有）
        const token = localStorage.getItem('token');

        // 使用fetch API从后端获取菜单数据
        fetch('/system/menu', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': token ? `Bearer ${token}` : ''
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码：${response.status}`);
                }
                return response.json();
            })
            .then(menuList => {
                if (menuList && menuList.length > 0) {
                    renderMenu(menuList);
                } else {
                    throw new Error('菜单数据为空');
                }
            })
            .catch(error => {
                console.error('获取菜单数据失败:', error);
                menuContainer.innerHTML = `
                <div class="p-4 text-center text-danger">
                    <i class="fa fa-exclamation-circle text-2xl mb-2"></i>
                    <p>菜单加载失败，请刷新页面重试</p>
                    <button class="mt-3 text-primary" onclick="loadMenu()">重新加载</button>
                </div>
            `;
                showToast('菜单加载失败', false);
            });
    }

    // 渲染菜单
    function renderMenu(menuList) {
        const menuContainer = document.getElementById('menu-container');
        menuContainer.innerHTML = '';

        menuList.forEach(menu => {
            if (menu.children && menu.children.length > 0) {
                // 有子菜单
                const submenuDiv = document.createElement('div');
                submenuDiv.className = 'mb-1';
                submenuDiv.innerHTML = `
                        <div class="menu-item cursor-pointer flex justify-between p-3 hover:bg-gray-100" onclick="toggleSubmenu('submenu-${menu.id}')">
                            <div class="flex items-center">
                                <i class="fa fa-folder w-5"></i>
                                <span class="ml-2">${menu.name}</span>
                            </div>
                            <i class="fa fa-angle-down transition-transform duration-300" id="arrow-${menu.id}"></i>
                        </div>
                        <div class="submenu hidden" id="submenu-${menu.id}">
                            ${menu.children.map(submenu => `
                                <a href="javascript:void(0)" class="submenu-item block p-3 hover:bg-gray-100" onclick="loadPage('${submenu.url}', '${submenu.name}', this)">
                                    <i class="fa fa-file-o w-5"></i>
                                    <span class="ml-2">${submenu.name}</span>
                                </a>
                            `).join('')}
                        </div>
                    `;
                menuContainer.appendChild(submenuDiv);
            } else {
                // 无子菜单
                const menuItem = document.createElement('a');
                menuItem.className = 'menu-item block p-3 hover:bg-gray-100';
                menuItem.href = "javascript:void(0)";
                menuItem.setAttribute('onclick', `loadPage('${menu.url}', '${menu.name}', this)`);
                menuItem.innerHTML = `
                        <i class="fa fa-file-o w-5"></i>
                        <span class="ml-2">${menu.name}</span>
                    `;
                menuContainer.appendChild(menuItem);
            }
        });

        // 默认展开第一个有子菜单的菜单项
        const firstSubmenu = document.querySelector('.submenu');
        const firstArrow = document.querySelector('.fa-angle-down');
        if (firstSubmenu && firstArrow) {
            firstSubmenu.classList.remove('hidden');
            firstArrow.classList.add('rotate-180');
        }
    }

    // 切换子菜单显示/隐藏
    function toggleSubmenu(submenuId) {
        const submenu = document.getElementById(submenuId);
        const arrow = document.getElementById(`arrow-${submenuId.split('-')[1]}`);

        if (submenu.classList.contains('hidden')) {
            submenu.classList.remove('hidden');
            arrow.classList.add('rotate-180');
        } else {
            submenu.classList.add('hidden');
            arrow.classList.remove('rotate-180');
        }
    }

    // 加载页面内容（修复后的版本）
    function loadPage(url, title, element) {
        console.log('Loading page:', url, title); // 添加日志以便调试

        // 在移动端关闭侧边栏
        if (window.innerWidth < 768) {
            document.getElementById('sidebar').classList.add('-translate-x-full');
            document.getElementById('sidebar-overlay').classList.add('hidden');
        }

        // 更新页面标题
        document.getElementById('page-title').textContent = title;
        document.getElementById('page-description').textContent = `您正在查看 ${title} 页面`;

        // 移除所有菜单项的活跃状态
        document.querySelectorAll('.menu-item, .submenu-item').forEach(item => {
            item.classList.remove('menu-active');
        });

        // 添加当前菜单项的活跃状态
        if (element) {
            element.classList.add('menu-active');
        } else {
            console.error('Element not provided to loadPage function');
        }

        // 显示加载提示
        const mainContent = document.querySelector('main');
        mainContent.innerHTML = `
            <div class="pt-6 pb-10 px-6">
                <h2 class="text-2xl font-bold text-gray-800 mb-4">${title}</h2>
                <div class="card">
                    <div class="flex flex-col items-center justify-center py-12">
                        <i class="fa fa-spinner fa-spin text-primary text-4xl mb-4"></i>
                        <p class="text-gray-600">正在加载 ${title} 页面内容...</p>
                    </div>
                </div>
            </div>
        `;

        // 模拟加载（实际项目中替换为AJAX）
        setTimeout(() => {
            mainContent.innerHTML = `
                <div class="pt-6 pb-10 px-6">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">${title}</h2>
                    <div class="card">
                        <div class="text-center">
                            <h3 class="text-xl font-medium text-gray-700 mb-2">${title}</h3>
                            <p class="text-gray-500">这是 ${title} 页面的内容区域</p>
                            <p class="text-gray-500 mt-2">URL: ${url}</p>
                        </div>
                    </div>
                </div>
            `;
        }, 800);
    }

    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        loadMenu();

        // 设置菜单样式
        document.head.insertAdjacentHTML('beforeend', `
            <style>
                .menu-item {
                    display: flex;
                    align-items: center;
                    padding: 10px 16px;
                    color: #333;
                    text-decoration: none;
                    transition: all 0.2s;
                }

                .menu-item:hover {
                    background-color: #f5f7fa;
                }

                .submenu-item {
                    display: flex;
                    align-items: center;
                    padding: 10px 16px 10px 32px;
                    color: #333;
                    text-decoration: none;
                    transition: all 0.2s;
                }

                .submenu-item:hover {
                    background-color: #f5f7fa;
                }

                .menu-active {
                    background-color: rgba(22, 93, 255, 0.1);
                    color: #165DFF;
                    border-left: 4px solid #165DFF;
                }
            </style>
        `);
    });
</script>
</body>
</html>